package youke.home.services;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class QuKLivetsService {
    private static final String API_URL = "http://api.quklive.com/cloud/open/activity/info";
    private static final String APP_KEY = "vu0klr7diqnncviq";  // 用您的实际appKey替换
    private static final String APP_SECRET = "9L4qmx3SAzT1ECN7"; // 用您的实际appSecret替换

    /**
     * 发送请求获得 new JsonNode
     */
    private JsonNode getJsonNode(Long liveId) throws IOException {
        // 设置请求头和请求体
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 获取时间戳
        long nonce = System.currentTimeMillis();

        // 生成签名
        String content = "appKey=" + APP_KEY + "&nonce=" + nonce;
        String signature = generateSignature(content);

        // 设置请求参数
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("appKey", APP_KEY);
        requestParams.put("nonce", nonce);
        requestParams.put("signature", signature);
        requestParams.put("id", liveId);

        // 创建请求体
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestParams, headers);;

        // 发送请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.POST, entity, String.class);

        // 处理返回结果
        JsonNode jsonNode = new ObjectMapper().readTree(response.getBody());
        System.out.println(jsonNode.toString());
        return jsonNode;
    }

    /**
     * 获取直播信息
     */
    public String getLiveInfo(long liveId) {
        List<String> tsUrls = new ArrayList<>();
        int isLive = 0;
        String currentHlsurl = "";
        int unchangedCount = 0;  // 记录连续tsUrls.size()不变的次数
        final int MAX_UNCHANGED_COUNT = 15;  // 设置最大不变次数为15
        try {
            JsonNode jsonNode = getJsonNode(liveId);
            if (jsonNode.get("code").asInt() == 0) {
                String hlsUrl = jsonNode.get("value").get("urlGroup").get("hlsUrl").asText();
                System.out.println("获取第一次的m3u8 地址: " + hlsUrl);
                while (true) {
                    JsonNode currentJsonNode = getJsonNode(liveId);
                    isLive = currentJsonNode.get("value").get("state").asInt();
                    currentHlsurl = currentJsonNode.get("value").get("urlGroup").get("hlsUrl").asText();
                    // 获取 m3u8 中的所有.ts 链接
                    List<String> newTsUrls = getTsUrlsFromM3u8(currentHlsurl);

                    // 记录之前的 tsUrls.size() 和当前的 tsUrls.size()
                    int prevSize = tsUrls.size();

                    for (String tsUrl : newTsUrls) {
                        if (!tsUrls.contains(tsUrl)) {  // 避免重复的 ts 链接
                            tsUrls.add(tsUrl);
                            System.out.println(tsUrl);
                        }
                    }
                    System.out.println("获取到 " + tsUrls.size() + " 个 .ts 文件链接");

                    // 如果 tsUrls.size() 没有变化，则增加 unchangedCount
                    if (tsUrls.size() == prevSize) {
                        unchangedCount++;
                    } else {
                        unchangedCount = 0;  // 重置计数器
                    }

                    // 如果连续15次没有变化，则结束循环
                    if (unchangedCount >= MAX_UNCHANGED_COUNT) {
                        System.out.println("tsUrls.size() 连续 15 次未变化，停止获取 .ts 文件链接");
                        break;
                    }

                    if (isLive == -1) {
                        System.out.println(tsUrls.toString());
                        System.out.println("直播结束！！！");
                        break;
                    }

                    Thread.sleep(1000);  // 每1秒检查一次
                }
                System.out.println("直播结束，停止获取 .ts 文件链接。");
                return tsUrls.toString();  // 返回获取到的 tsUrls 列表
            } else {
                return "请求失败: " + jsonNode.get("msg").asText();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "获取直播信息时发生错误";
        }
    }


    /**
     * 从给定的 m3u8 链接中获取所有.ts 链接
     */
    private List<String> getTsUrlsFromM3u8(String m3u8Url) throws IOException {
        List<String> tsUrls = new ArrayList<>();
        URL url = new URL(m3u8Url);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine())!= null) {
                if (line.endsWith(".ts")) {
                    tsUrls.add(line);
                }
            }
            reader.close();
            connection.disconnect();
            return tsUrls;
        } catch (FileNotFoundException fileNotFoundException) {
            System.out.println(tsUrls);
            return tsUrls;
        }
    }

    /**
     * 生成签名
     */
    private String generateSignature(String content) {
        try {
            byte[] hmacSha1 = HmacUtils.hmacSha1(APP_SECRET, content);
            return Base64.encodeBase64String(hmacSha1);
        } catch (Exception e) {
            System.err.println("签名生成失败: " + e.getMessage());
            return null;
        }
    }
}
